// 引入 router 在vuex内使用router跳转
import router from '@/router'
import asyncRouterMap from '@/router/async'
import requset from '@/assets/js/requset'

let menuKeyStr = 'navmenu'
let menuStr = window.sessionStorage.getItem(menuKeyStr)
let menuVal = {}
if (menuStr) {
    menuVal = JSON.parse(menuStr)
}
const navMenus = {
    // 如果为true---->调用方法需添加命名空间 如tabviews/createTab
    namespaced: true,
    state: {
        leftMenus: menuVal.leftMenus || [],
        rootUrl: menuVal.rootUrl || ["/"],
        permissions: menuVal.permissions || [],
    },

    // dispatch 触发--->actions 异步变更
    actions: {
        //  请求获取菜单栏目
        requestMenus({ commit, state }, data) {
            commit('RQQUEST_MENUS', data)
        },
        // 获取登录后菜单栏目信息
        getMenus({ commit, state }) {
            if (state.leftMenus.length == 0) {
                let menuStr = window.sessionStorage.getItem(menuKeyStr)
                state.leftMenus = JSON.parse(menuStr).leftMenus
            }

            return new Promise((resolve) => {
                resolve(state.leftMenus)
            })
        },
        // 获取用户权限
        getPermissions({ commit, state }) {
            if (state.permissions.length == 0) {
                let menuStr = window.sessionStorage.getItem(menuKeyStr)
                state.permissions = JSON.parse(menuStr).permissions
            }

            return new Promise((resolve) => {
                resolve(state.permissions)
            })
        },
        removeMenus({ commit, state }) {
            state.leftMenus = []
            window.sessionStorage.removeItem(menuKeyStr)
        },
        addTabs({ commit, state }, url) {
            return new Promise((resolve) => {
                let tab = childenSearch(state.leftMenus, url)
                if (tab) {
                    delete tab.childen
                    resolve(tab)
                } else {
                    resolve(null)
                }
            })
        }
    },
    // 外部方法 commit触发--->mutaions  同步变更
    mutations: {
        RQQUEST_MENUS(state, data) {
            // 验证是否登录
            if (data) {
                this.dispatch('app/logAction', data)
                this.dispatch('tabs/setTabs', { clear: true })

                //遍历左侧菜单栏目                
                // 获取菜单目录--暂时注释
                requset.post("/api/role/MyMenus", "", res => {

                    let list = res.Data;
                    // menukeyInfo.basePath = "Url"
                    // menukeyInfo.permission = "Code"
                    // menukeyInfo.pkid = "NodeId"
                    firstTab = null

                    //遍历左侧菜单栏目
                    ForMenu(list, asyncRouterMap)
                    state.leftMenus = list
                    // if (firstTab) {
                    //     this.dispatch('tabs/openTabs', firstTab)
                    // }

                    window.sessionStorage.setItem(menuKeyStr, JSON.stringify(state))

                    //添加默认
                    this.dispatch("tabs/addTabs",
                        {
                            icon: "el-icon-tickets",
                            title: "首页",
                            basePath: "/welcome",
                            index: "welcome",
                            name: "welcome",
                            closable: false
                        }
                    );

                    //获取权限
                    requset.post("/api/role/MyBtns", "", res1 => {
                        let btns = res1.Data;
                        let menuPerMissions = []
                        btns.forEach(btn => {
                            menuPerMissions.push({
                                Name: btn.BtnName,
                                permission: btn.BtnCode
                            })
                        });

                        // //获取路由权限
                        // let menuPerMissions = []

                        //缓存赋值
                        state.permissions = menuPerMissions
                        window.sessionStorage.setItem(menuKeyStr, JSON.stringify(state))
                    });
                })

                // // 获取菜单目录
                // let apiMenus = [{
                //     title: '系统管理',
                //     icon: 'el-icon-tickets',
                //     basePath: '',
                //     index: 'rootmenu',
                //     children: [ {
                //         icon: '',
                //         title: '菜单管理',
                //         basePath: '/sysmenu'
                //     }, {
                //         icon: '',
                //         title: '用户管理',
                //         basePath: '/sysmanage'
                //     }, {
                //         icon: '',
                //         title: '角色管理',
                //         basePath: '/sysrole'
                //     }]
                // }, {
                //     title: '代码示例',
                //     icon: 'el-icon-tickets',
                //     basePath: '',
                //     index: 'coder',
                //     children: [{
                //         icon: '',
                //         title: '表单',
                //         basePath: '/form'
                //     }, {
                //         icon: '',
                //         title: '表格更新',
                //         basePath: '/tableUpdate'
                //     }, {
                //         icon: '',
                //         title: '表单表格',
                //         basePath: '/formtable'
                //     }, {
                //         icon: '',
                //         title: '属性tree',
                //         basePath: '/tree'
                //     }, {
                //         icon: '',
                //         title: 'tree表格',
                //         basePath: '/treetable'
                //     }, {
                //         icon: '',
                //         title: '表格',
                //         basePath: '/table'
                //     }]
                // }]

                // ForMenu(apiMenus, asyncRouterMap)
                // state.leftMenus = apiMenus

                // window.sessionStorage.setItem(menuKeyStr, JSON.stringify(state))
                // //获取菜单后跳转首页

                // //添加默认
                // this.dispatch("tabs/addTabs",
                //     {
                //         icon: "el-icon-tickets",
                //         title: "首页",
                //         basePath: "/welcome",
                //         index: "welcome",
                //         name: "welcome",
                //         closable: false
                //     }
                // );
            }
        }
    }
}


//菜单key说明  便于调整通用使用方法
let menukeyInfo = {
    index: 'NodeId', //activeIndex 选项卡标识
    title: 'Text', //菜单目录名称
    name: 'name',//子菜单名称
    basePath: 'Url',//界面路由
    children: 'children',//菜单子级
    icon: 'Icon',//菜单图标
}

//显示第一个选项卡
let firstTab = null
// //所有界面功能得权限按钮
let menuPerMissions = []

//递归遍历菜单
const getTree = function (pstr, id, data) {
    let ent = data.filter((c) => c[menukeyInfo.basePath] == id)[0];
    data.forEach((x) => {
        //添加界面权限按钮
        let basePath = x[menukeyInfo.basePath]
        if (x[menukeyInfo.permission].length > 0 && (basePath || basePath != "/")) {
            if (menuPerMissions.filter(c => c.basePath != basePath).length == 0) {
                menuPerMissions.push({
                    basePath: basePath,
                    permission: x.permission
                })
            }
        }

        if (x[pstr] == id) {
            if (!x[menukeyInfo.basePath]) delete x[menukeyInfo.basePath];
            ent.children.push(x);
            getTree(pstr, x[menukeyInfo.basePath], data);
        }
    });
}



// 遍历菜单目录方法 list数据集合  entitys路由数据配置
const ForMenu = function (list, entitys) {
    list.forEach((menu) => {
        //赋值title
        menu.title = menu[menukeyInfo.title]
        //赋值index
        menu.index = menu[menukeyInfo.index]
        let pageindex = Math.ceil(Math.random() * 9999999).toString();
        if (menu[menukeyInfo.icon]) {
            menu.icon = menu[menukeyInfo.icon]
        }

        //删除对象不需要属性
        Object.keys(menu).forEach(key => {
            if (key != 'title' && key != 'icon' && key != menukeyInfo.index && key != menukeyInfo.title && key != menukeyInfo.basePath && key != menukeyInfo.children && key != menukeyInfo.icon) {
                delete menu[key]
            }
        })

        //子级验证
        if (menu[menukeyInfo.children] && menu[menukeyInfo.children].length > 0) {
            //赋值icon
            if (!menu.icon) {
                menu.icon = 'el-icon-folder'
            }
            if (!menu.index) {
                menu.index = pageindex
            }
            ForMenu(menu[menukeyInfo.children], entitys)
        } else {
            delete menu[menukeyInfo.children]

            // let pageMenu = entitys.filter((c) => { return (c.path.indexOf(menu[menukeyInfo.basePath]) >= 0 || menu[menukeyInfo.basePath].indexOf(c.path) >= 0) })
            let pageMenu = entitys.filter((c) => { return (c.path == menu[menukeyInfo.basePath]) })

            let basePath = menu[menukeyInfo.basePath]
            //添加路由权限
            if (basePath) {
                if (navMenus.state.rootUrl.indexOf(pageindex) < 0) {
                    navMenus.state.rootUrl.push(pageindex)
                }
                //赋值basePath
                menu.basePath = basePath
            }

            //如果匹配到路由配置则使用路由配置=》index唯一
            if (pageMenu && pageMenu.length > 0) {
                pageindex = pageMenu[0].name
            }

            //赋值index
            menu.index = pageindex
            if (!menu.name) {
                menu.name = pageindex
            }

            menu.closable = true
            //赋值icon
            if (!menu.icon) {
                console.log(113332211)
                menu.icon = 'el-icon-tickets'
            }

            //默认第一个
            if (!firstTab) {
                firstTab = menu
            }
        }
    })
}

// 递归查询
function childenSearch(data, url) {
    if (data.length > 0) {
        let model
        // 检索是否匹配
        let ents = data.filter(c => url == c.basePath)
        if (ents.length > 0) {
            model = ents[0]
        } else {
            data.forEach(ent => {
                if (ent.childen && ent.childen.length > 0) {
                    model = childenSearch(ent.childen, url)
                }
            })
        }

        return model
    }
}

export default navMenus